package com.chuangyiruanke.util;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class CSVReader implements Closeable {

  private char seperator;
  private BufferedReader reader;

  public char getSeperator() {
    return seperator;
  }

  public void setSeperator(char seperator) {
    this.seperator = seperator;
  }

  public CSVReader(InputStream inputStream) {
    this(inputStream, Charset.defaultCharset());
  }

  public CSVReader(InputStream inputStream, String charsetName) {
    this(inputStream, Charset.forName(charsetName));
  }

  public CSVReader(InputStream inputStream, Charset charset) {
    reader = new BufferedReader(new InputStreamReader(inputStream, charset));
    this.seperator = ',';
  }


  @Override
  public void close() throws IOException {
    reader.close();
  }

  public String readLine() throws IOException {
    return reader.readLine();
  }

  public String[] readNexRow() throws IOException {
    String line = reader.readLine();
    if (line == null) {
      return null;
    }
    List<String> list = new ArrayList<>(200);
    int first = -1;

    int length = line.length();
    boolean inQuota = false;
    for (int i = 0; i < length; i++) {
      if (first == -1) {
        first = i;
      }
      char ch = line.charAt(i);
      if (ch == '"') {
        if (i >= length - 1 || line.charAt(i + 1) != '"') {
          inQuota = !inQuota;
        } else {
          i++;
        }
      } else if (ch == seperator) {
        if (!inQuota) {
          String val = line.substring(first, i);
          if (val.startsWith("\"") && val.endsWith("\"")) {
            val = val.substring(1, val.length() - 1);
          }
          list.add(val.replaceAll("\"\"", "\""));
          first = -1;
        }
      }
    }
    if (first != -1) {
      list.add(line.substring(first, length));
    }
    String[] result = new String[list.size()];
    return list.toArray(result);
  }
}
